package com.edu.websocket;

import org.springframework.http.HttpRequest;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * writer: shiku_li
 * Time: 2018-06-08
 * Intent: webSocket服务器
 */
@ServerEndpoint("/webSocket/chat/{roomName}")
@Component
public class WsServer {

    // 使用map来收集session，key为roomName，value为同一个房间的用户集合
    // concurrentMap的key不存在时报错，不是返回null
    private static final Map<String, Set<Session>> rooms = new ConcurrentHashMap();
    @OnOpen
    public void connect(@PathParam("roomName") String roomName, Session session) throws Exception {
        // 将session按照房间名来存储，将各个房间的用户隔离
        if (!rooms.containsKey(roomName)) {
            // 创建房间不存在时，创建房间
            Set<Session> room = new HashSet<>();
            // 添加用户
            room.add(session);
            rooms.put(roomName, room);
        } else {
            // 房间已存在，直接添加用户到相应的房间
            rooms.get(roomName).add(session);
        }
        System.out.println("a client has connected!");
    }

    @OnClose
    public void disConnect(@PathParam("roomName") String roomName, Session session) {
        rooms.get(roomName).remove(session);
        System.out.println("a client has disconnected!");
    }

    @OnMessage
    public void receiveMsg(@PathParam("roomName") String roomName,
                           String msg, Session session) throws Exception {

        //创建时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date =new Date();
        String time = simpleDateFormat.format(date);
        String message;
        String[] pang = new String[2];
        pang =  msg.split(";");
        //可以在此保存数据到数据库

        for (Session session1 : rooms.get(roomName)) {
            //判断是否发送给自己
            if(session1.equals(session)) {
                //发送给自己
                message = "<div class='chat-message-right'><div class='message'><span class='message-date'> "+time+" </span><br/><a class='message-author'> 我&nbsp;&nbsp;说：&nbsp;&nbsp;</a><span class='message-content'>"+pang[0]+"</span></div></div>";
            }else {
                //发送给别人
                message = "<div class='chat-message-left'><div class='message'><span class='message-date'> "+time+" </span><br/><a class='message-author'> "+pang[1]+"&nbsp;&nbsp;说：&nbsp;&nbsp;</a><span class='message-content'>"+pang[0]+"</span></div></div>";
            }
            //发送
            session1.getBasicRemote().sendText(message);

        }
    }


}